//
//  ADWebViewController.m
//  ADKit
//
//  Created by 杜 泽旭 on 2017/12/3.
//  Copyright © 2017年 duzexu. All rights reserved.
//

#import "ADWebViewController.h"
#import "ADKitHeaders.h"

/// KVO 监听的属性
/// 加载情况
static NSString * const ADWebViewKVOLoading = @"loading";
/// 文章标题
static NSString * const ADWebViewKVOTitle = @"title";
/// 进度
static NSString * const ADWebViewKVOEstimatedProgress = @"estimatedProgress";

@interface ADWebViewController () {
    FBKVOController *_KVOController;
}

@property (nonatomic, weak, readwrite) WKWebView *webView;
@property (nonatomic, readwrite, strong) UIProgressView *progressView;
@property (nonatomic, strong, readonly) ADWebViewModel *viewModel;

@end

@implementation ADWebViewController
@dynamic viewModel;

- (void)dealloc {
    [_webView stopLoading];
}

- (void)initialize {
    [super initialize];
    /// 注册JS
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.preferences = [[WKPreferences alloc] init];
    
    configuration.allowsInlineMediaPlayback = YES;
    configuration.mediaPlaybackRequiresUserAction = NO;
    
    configuration.preferences.minimumFontSize = 10;
    
    configuration.preferences.javaScriptEnabled = YES;
    
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    configuration.processPool = [[WKProcessPool alloc] init];
    
    configuration.userContentController = userContentController;
    
    configuration.processPool = [[WKProcessPool alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    webView.navigationDelegate = self.viewModel;
    webView.UIDelegate = self.viewModel;
    
    self.webView = webView;
    [self.view addSubview:webView];
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(self.viewModel.webViewViewInset);
    }];
    
    /// 监听数据
    _KVOController = [FBKVOController controllerWithObserver:self];
    @weakify(self);
    [_KVOController observe:self.webView keyPath:ADWebViewKVOTitle options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        @strongify(self);
        if (!self.viewModel.shouldDisableWebViewTitle) self.navigationItem.title = self.webView.title;
        self.viewModel.title = self.webView.title;
    }];
    [_KVOController observe:self.webView keyPath:ADWebViewKVOLoading options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        
    }];
    [_KVOController observe:self.webView keyPath:ADWebViewKVOEstimatedProgress options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        @strongify(self);
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if(self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }];
    
    /// 添加刷新控件
    if(self.viewModel.shouldPullDownToRefresh) {
        Class cls = self.viewModel.refreshHeaderClass;
        MJRefreshHeader *header;
        if (cls) {
            header = [cls headerWithRefreshingBlock:^{
                @strongify(self);
                [self.webView reload];
            }];
        }else{
            header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                @strongify(self);
                [self.webView reload];
            }];
        }
        self.webView.scrollView.mj_header = header;
        [self.webView.scrollView.mj_header beginRefreshing];
    }
}

- (void)bindViewModel {
    [super bindViewModel];
    if (self.viewModel.request) {
        [self.webView loadRequest:self.viewModel.request];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController.navigationBar addSubview:self.progressView];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.progressView removeFromSuperview];
}

#pragma mark - Getter & Setter
- (UIProgressView *)progressView {
    if (!_progressView) {
        CGFloat progressViewW = AD_SCREEN_WIDTH;
        CGFloat progressViewH = 3;
        CGFloat progressViewX = 0;
        CGFloat progressViewY = CGRectGetHeight(self.navigationController.navigationBar.frame) - progressViewH + 1;
        UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(progressViewX, progressViewY, progressViewW, progressViewH)];
        [self.view addSubview:progressView];
        self.progressView = progressView;
    }
    return _progressView;
}

@end
